package com.xjzd.spring.global;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) {
        System.out.println("[methodArgumentNotValidExceptionExceptionHandler]" + ex);
        // 获取 errorMessage
        String errorMessage = null;
        FieldError fieldError = ex.getBindingResult().getFieldError();
        if (fieldError == null) {
            // 组合校验，参考自 https://t.zsxq.com/3HVTx
            List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
            if (!CollectionUtils.isEmpty(allErrors)) {
                errorMessage = allErrors.get(0).getDefaultMessage();
            }
        } else {
            errorMessage = fieldError.getDefaultMessage();
        }
        // 转换 CommonResult
        if (!StringUtils.hasText(errorMessage)) {
            return ResponseEntity.badRequest().body(errorMessage);
        }
        return ResponseEntity.badRequest().body(String.format("请求参数不正确:%s", errorMessage));
    }

    @ExceptionHandler(HandlerMethodValidationException.class)
    public void global(HandlerMethodValidationException e) {
        log.error("e: {}", e.getParameterValidationResults());
    }
}
